const api = require('../../common/api');


const fabric_query = require('../../common/service/fabric_query');
const fabric_util = require('../../common/service/fabric_util');
const myJson = require('../../common/json');


module.exports = {

    list: async function (ctx) {
        let condition = {};
        if (!api.isset(ctx.request.query, ["pageNo"])) {
            ctx.body = {"error_code": 20000, "error_msg": "parameters is not enough!"};
            return;
        }else{
            condition.PageNo = Number(ctx.request.query.pageNo);
        }
        // condition.Table = "entity";  // entity.go里没有定义table  lionel  {而原先是根据这个去查的}
        if (ctx.request.query.DEDKey !== undefined && ctx.request.query.DEDKey !== "") {
            condition.DEDKey = ctx.request.query.DEDKey;
        }else{
            ctx.body = {"error_code": 20000, "error_msg": "parameters is not enough!"};
            return;
        }
        if (ctx.request.query.DEEKey !== undefined && ctx.request.query.DEEKey !== "") {
            condition.DEEKey = ctx.request.query.DEEKey;
        }
        let args = [JSON.stringify(condition)];
        let obj = fabric_util.getObj("department", "DESelect", args);

        let res = await fabric_query.query(obj).then((res) => {
            return res;
        });
        if (myJson.isJSON(res)) {
            ctx.body = {
                "error_code": 0,
                "data": {
                    "list": JSON.parse(res)
                }
            }
        } else {
            ctx.body = {
                "error_code": 20000,
                "error_msg": res
            }
        }

    },

    add: async function (ctx) {
        let condition = {};
        let condition2 = [];
        let sLen = 0;
        let dKey = ctx.request.body.DepartmentKey;
        if (!api.isset(ctx.request.body, ["EntityName", "DepartmentKey", "Number"])) {
            ctx.body = {"error_code": 20000, "error_msg": "parameters is not enough!"};
            return;
        }
        condition.EntityName = ctx.request.body.EntityName;
        condition.DepartmentKey = ctx.request.body.DepartmentKey;
        condition.Number = parseInt(ctx.request.body.Number);  // 在链码里定义为int了，这里需要转换一下
        condition.Table = "entity";

        if (ctx.request.body.Parent !== undefined || ctx.request.body.Parent !== "") {
            // 将字符串分隔以分别为标识符；
            let s = ctx.request.body.Parent;
            sLen = 1;
            sLen = s.split(";").length;
            //for(var i in ctx.request.body.Parent){  // 这是个遍历字符串的长度，就不对了，应该遍历分割的长度
            for (let i = 0; i < sLen; i++) {
                let param = {};
                let a = s.split(";")[i];  // 取到;前第0个值
                param.Key = a.slice(0, a.lastIndexOf(",")).toString();
                param.Number = parseInt(a.slice(a.lastIndexOf(",") + 1, a.length).toString());
                //param.Key = ctx.request.body.Parent[i].Key;
                //param.Number = parseInt(ctx.request.body.Parent[i].Number);
//                param.Number =10;
                //param.Number = parseInt("ctx.request.body.Parent[i].Number");
                condition2[i] = param
            }
        }
        let args = [];
        //if (condition2.length > 0) {   // 这个条件>0的话，还是会追加一个空串的
        if(sLen > 1){
            args = [JSON.stringify(condition), JSON.stringify(condition2)];
        } else {
            args = [JSON.stringify(condition)];
        }
        let obj = fabric_util.getObj("entity", "EntityAdd", args);

        let res = await fabric_query.invoke(obj).then((res) => {
            return res;
        });

        // 再往de里添加 added by lionel
        let conditionDE = {};
        conditionDE.DEDKey = ctx.request.body.departmentKey;
        conditionDE.DEDkey = dKey;
        conditionDE.DEEKey = "1567559113";
        conditionDE.table  = "de";
        let argsDE;  // let argsDE = []; // warn variable initializer is redundant
        argsDE = [JSON.stringify(conditionDE)];
        let objDE = fabric_util.getObj("department", "DEAdd", argsDE);
        let resDE = await fabric_query.invoke(objDE).then((resDE) => {
            return resDE;
        });
        // res+=resDE; // 再拼成一个新的res*/

        // end
        ctx.body = {
            error_code: 0,
            data: res, resDE
        }
    },

    addSocket: async function (socket) {
        const enetity = require("./entity");

        socket.on('addEntity', function (data) {
            enetity.addEntity(data, socket)
        });
    },

    addEntity: async function (entity, socket) {

        let condition = [];
        if (!api.isset(entity, ["EntityName", "DepartmentKey", "Number"])) {
            //ctx.body = {"error_code": 20000, "error_msg": "parameters is not enough!"};
            let res = {};
            res.code = 0;
            res.res = "parameters is not enough!";
            socket.emit('res', res);
            return
        }

        entity.Number = parseInt(entity.Number);  // 在链码里定义为int了，这里需要转换一下
        entity.Table = "entity";
        if (entity.Parent !== undefined && entity.Parent !== '') {
            for (let i in entity.body.Parent) {
                let param = {};
                param.Key = ctx.request.body.Parent[i].Key;
                param.Number = ctx.request.body.Parent[i].Number;
                //param.Number = parseInt("ctx.request.body.Parent[i].Number");
                condition[i] = param
            }
        }
        let args = [];
        if (condition.length > 0) {
            args = [JSON.stringify(entity), JSON.stringify(condition)];
        } else {
            args = [JSON.stringify(entity)];
        }

        let obj = fabric_util.getObj("entity", "EntityAdd", args);

        await fabric_query.invoke(obj).then((result) => {
          //  console.log("321312", result)
            //  console.log("123123",res)
            socket.emit('res', result);
            //执行数据库的操作
          //  if (result.code === 0) {
                // console.log("res.code=0")
                // let fields = {}
                // fields.TxID = result.tx_id;
                // fields.DK = entity.DepartmentKey;
                // fields.EK = Buffer.from(result.res[0].response.payload).toString();
                // Date.prototype.Format = function (fmt) { //author: meizz
                //     var o = {
                //         "M+": this.getMonth() + 1, //月份
                //         "d+": this.getDate(), //日
                //         "h+": this.getHours(), //小时
                //         "m+": this.getMinutes(), //分
                //         "s+": this.getSeconds(), //秒
                //         "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                //         "S": this.getMilliseconds() //毫秒
                //     };
                //     if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                //     for (var k in o)
                //         if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                //     return fmt;
                // }
                // fields.CreateTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
                // countDao.countAdd(fields).then((sqlRes) => {
                //     if (sqlRes.err === undefined) {
                //         console.log("add to mysql success")
                //     } else {
                //         console.log("add to mysql failed")
                //     }
                // });
            // } else {
            //     console.log("invoke failed,can`t insert into mysql")
            // }
        });


    },

    update: async function (ctx) {
        /*if (!api.isset(ctx.request.body, ["Key"])) {
            ctx.body = {"error_code": 20000, "error_msg": "parameters is not enough!"};
            return;
        }*/
        let condition = {};
        if (ctx.request.body.EntityName !== undefined && ctx.request.body.EntityName !== "") {
            condition.EntityName = ctx.request.body.EntityName;
        }
        if (ctx.request.body.DepartmentKey !== undefined && ctx.request.body.DepartmentKey !== "") {
            condition.DepartmentKey = ctx.request.body.DepartmentKey;
        }
        if (ctx.request.body.Number !==undefined && ctx.request.body.Number !== "") {
            condition.Number = parseInt(ctx.request.body.Number);
            //condition.Number = 100;
        }
        condition.Key = "1615660950";

        //let args = [ctx.request.body.key,JSON.stringify(condition)];
        let args = [JSON.stringify(condition)];
        let obj = fabric_util.getObj("entity", "EntityUpdate", args);

        let res = await fabric_query.invoke(obj).then((res) => {
            return res;
        });
        ctx.body = {
            error_code: 0,
            data: res
        }
    },

};